<script setup>
import {ref} from 'vue'
import {UploadFilled} from '@element-plus/icons-vue'
import {usePcKeyStore} from "@/stores/pckey.js";

const pcKeyStore = usePcKeyStore()

const fileList = ref([])
const upload = ref()

const onBeforeUpload = (file) => {
  const isType = file.type === 'application/json';
  const isLt500K = file.size / 1024 < 500;

  if (!isType) {
    ElMessage.error('上传文件只能是json格式!');
  } else if (!isLt500K) {
    ElMessage.error('上传文件大小不能超过 500KB!');
  }
  return isType && isLt500K;
}

const onExceed = (files) => {
  upload.value.clearFiles()
  upload.value.handleStart(files[0])
  upload.value.submit()
}

const onSuccess = (response) => {
  pcKeyStore.pckey = response
  ElMessage.success("上传成功!")
  // console.log(file);
}

const onError = () => {
  ElMessage.error("上传失败！")
}

</script>

<template>
  <el-upload
      ref="upload"
      :before-upload="onBeforeUpload"
      :file-list="fileList"
      :limit="1"
      :on-error="onError"
      :on-exceed="onExceed"
      :on-success="onSuccess"
      accept="application/json"
      action="/api/uploadJsonFile"
      class="upload01"
      drag
      method="post"
  >
    <template #trigger>
      <el-icon class="el-icon--upload">
        <upload-filled/>
      </el-icon>
      <div class="el-upload__text">
        拖拽文件 或 <em>点击上传</em>
      </div>
    </template>
    <template #tip>
      <div class="el-upload__tip">
        第五人格键位文件pc_key_setting_data.json<br>
      </div>
    </template>
  </el-upload>


</template>

<style scoped>
* {
  margin: 0;
  padding: 0;
}
</style>